package cn.stylefeng.guns.modular.business.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.config.redis.redis.Redis2Template;
import cn.stylefeng.guns.config.redis.redis.util.Redishandler2;
import cn.stylefeng.guns.core.RecoverConst;
import cn.stylefeng.guns.modular.business.common.GunsData;
import cn.stylefeng.guns.modular.business.entity.CardQuota;
import cn.stylefeng.guns.modular.business.mapper.CardQuotaMapper;
import cn.stylefeng.guns.modular.business.model.params.CardQuotaParam;
import cn.stylefeng.guns.modular.business.model.result.CardQuotaResult;
import cn.stylefeng.guns.modular.business.service.CardQuotaService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 卡面值 服务实现类
 * </p>
 *
 * @author jwj
 * @since 2019-07-12
 */
@Service
@Slf4j
public class CardQuotaServiceImpl extends ServiceImpl<CardQuotaMapper, CardQuota> implements CardQuotaService {

    @Autowired
    private Redishandler2 redishandler2;

    @Autowired
    private Redis2Template redis2Template;


    @Override
    public void add(CardQuotaParam param){
        CardQuota entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(CardQuotaParam param){
        CardQuota entity = new CardQuota();
        entity.setCardQuotaId(param.getCardQuotaId());
        entity.setDeleteFlag(RecoverConst.DEL_FLAG_TRUE);
        this.updateById(entity);
    }

    @Override
    public void update(CardQuotaParam param){
        CardQuota oldEntity = getOldEntity(param);
        CardQuota newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public CardQuotaResult findBySpec(CardQuotaParam param){
        return null;
    }

    @Override
    public List<CardQuotaResult> findListBySpec(CardQuotaParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(CardQuotaParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 更新状态
     *
     * @param param
     * @author jwj
     * @Date 2019-07-12
     */
    @Override
    public void status(CardQuotaParam param) {
        CardQuota entity = new CardQuota();
        entity.setCardQuotaId(param.getCardQuotaId());
        entity.setStatus(param.getStatus());
        this.updateById(entity);
    }

    /**
     * 初始化缓存面值
     */
    @Override
    public void initCacheQuota() {
        log.info("初始化分类下的面值缓存");
        List<CardQuota> cardQuotaList = this.list(new QueryWrapper<CardQuota>().eq("delete_flag", RecoverConst.DEL_FLAG_FALSE).eq("status", RecoverConst.CARD_QUOTA_STATU_ENABLE).orderByAsc("amount"));
        Map<Long, List<CardQuota>> map = new HashMap<>();
        for (CardQuota cardQuota : cardQuotaList) {
            if (map.get(cardQuota.getCataoryId()) != null) {
                map.get(cardQuota.getCataoryId()).add(cardQuota);
            } else {
                List<CardQuota> quotaResults = new ArrayList<>();
                quotaResults.add(cardQuota);
                map.put(cardQuota.getCataoryId(), quotaResults);
            }
        }
        //初始化缓存
        List<Object> redisResult = redis2Template.executePipelined(new RedisCallback<Object>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.del(RecoverConst.QUOTA_HASH_KEY.getBytes());
                for(Long key : map.keySet()) {
                    connection.del((RecoverConst.QUOTA_STR_KEY + key).getBytes());
                    connection.set((RecoverConst.QUOTA_STR_KEY + key).getBytes() , JSONObject.toJSONString(map.get(key)).getBytes());
                    for (CardQuota cardFrontQuotaResult : map.get(key)) {
                        connection.hSet(RecoverConst.QUOTA_HASH_KEY.getBytes(), cardFrontQuotaResult.getCardQuotaId().toString().getBytes(), JSONObject.toJSONString(cardFrontQuotaResult).getBytes());
                    }
                }
                return null;
            }
        });
        //清楚面值缓存
        GunsData.cardAndQuotaList.clear();
    }

    private Serializable getKey(CardQuotaParam param){
        return param.getCardQuotaId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private CardQuota getOldEntity(CardQuotaParam param) {
        return this.getById(getKey(param));
    }

    private CardQuota getEntity(CardQuotaParam param) {
        CardQuota entity = new CardQuota();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
